import ContentCopyIcon from '@mui/icons-material/ContentCopy';
import { LoadingButton } from '@mui/lab';
import {
    Box,
    Button,
    Card,
    Checkbox,
    Dialog,
    DialogContent,
    DialogTitle,
    FormControlLabel,
    TextField,
    Typography
} from '@mui/material';
import React, { ChangeEvent, useCallback, useContext, useState } from 'react';
import create from 'zustand';

import PaymentManager from '../../../../api/payment/payment-manager';
import Config from '../../../../config';
import Routes from '../../../../constants/routes';
import NumberTool from '../../../../libs/number-tool';
import { getTotalAmount } from '../../../../libs/utilities';
import { isTransactionHashInvalid } from '../../../../libs/validate';
import Countdown from '../../countdown';
import { DialogContext } from '../dynamic-dialogs';
import { useStyles } from '../UIs/styled-mui-dialog';

type PayDisburseStore = {
    open: boolean;
    close?: () => void;
    data: any;
    onSubmit?: () => void;
};

const usePayStore = create<PayDisburseStore>((set) => ({
    open: false,
    close: () => set({ open: false }),
    data: {},
    onSubmit: undefined
}));

export const payDisbursementDialog = ({ open, data, onSubmit }: PayDisburseStore) => {
    usePayStore.setState({
        open,
        data,
        onSubmit
    });
};

export const PayDisbursementDialog = () => {
    const [address] = useState<string>('ronin:349bd28d26bd1647b1bffc726f23a52671551803');
    const [hash, setHash] = useState<string>(undefined);
    const [loading, setLoading] = useState<boolean>(false);
    const [isTimeout, setIstimeout] = useState<boolean>(false);
    const [error, setError] = useState<{ code: string; message: string }>(null);
    const [confirmed, setConfirmed] = useState<boolean>(false);
    const style = useStyles();
    const { open, close, data, onSubmit } = usePayStore();
    const {
        transactions = [],
        token = '',
        disbursement = {},
        transactionFee = 0,
        network = null
    } = data;
    const { value } = useContext(DialogContext);

    const getTotalFee = (): number => {
        return getFee() * transactions.length;
    };

    const getFee = (): number => {
        return token === 'SLP' ? transactionFee : 0;
    };

    const submit = async () => {
        if (!address || isTransactionHashInvalid(hash)) {
            return;
        }
        setLoading(true);
        try {
            await PaymentManager.setTransactionHash(disbursement.id, hash, token, network.id).then(
                () => {
                    close();
                    onSubmit();
                }
            );
        } catch (e) {
            setError(e);
        } finally {
            setLoading(false);
        }
    };

    const getTokenIcon = () => {
        return Config.getAPI() + '/images/coins/' + token + '.png';
    };

    const onCopy = async () => {
        await navigator.clipboard.writeText(address);
        alert('Copied the transaction hash of ' + address);
    };

    const onTimeout = useCallback(() => {
        setIstimeout(true);
    }, []);

    const onChangeHash = (event: ChangeEvent<HTMLInputElement>) => {
        const hash = event.target?.value;
        if (isHashInvalid(hash)) {
            setError({ code: '', message: 'Invalid transaction hash' });
        } else {
            setError(undefined);
        }
        setHash(hash);
    };

    const isHashInvalid = (hash: string) => hash !== undefined && isTransactionHashInvalid(hash);

    return (
        <Dialog open={open} maxWidth="sm" fullWidth disableEscapeKeyDown={true}>
            <Box className={`${style.dialogBackground} ${style.center}`}>
                <DialogTitle className={style.textTitle}>Pay</DialogTitle>
            </Box>
            <DialogContent className={`${style.dialogBackground} ${style.center}`}>
                <div className="p-4">
                    {!isTimeout && (
                        <Typography
                            variant="h6"
                            align={'center'}
                            color="white"
                            sx={{ pb: 1, marginTop: '-1rem', marginBottom: '1rem' }}
                        >
                            Price is locked. You have{' '}
                            <span style={{ color: 'var(--color-warning)' }}>
                                <Countdown timer={value.time} onTimeout={onTimeout} /> minutes
                            </span>{' '}
                            to complete this transaction
                        </Typography>
                    )}
                    <Typography variant="h6" color="white" sx={{ pb: 1 }}>
                        Total amount to pay
                    </Typography>
                    <Card className={style.card}>
                        <Box className={style.center}>
                            <Typography
                                variant="body1"
                                className={style.textContent}
                                align="center"
                            >
                                {NumberTool.format(
                                    getTotalAmount(transactions) + getTotalFee(),
                                    token,
                                    2
                                )}{' '}
                                {token}
                            </Typography>
                            <Box
                                component="img"
                                className={style.icon}
                                alt="Icon"
                                src={getTokenIcon()}
                            />
                        </Box>
                    </Card>
                    <Typography variant="h6" color="white" sx={{ pb: 1, mt: 2 }}>
                        Send Payments to
                    </Typography>
                    <Card className={style.card}>
                        <Typography variant="body1" color="#EEEEEE" sx={{ pb: 1, fontSize: 14 }}>
                            XLD RONIN WALLET
                        </Typography>
                        <Box display="flex" alignItems="center" justifyContent="space-between">
                            <Typography variant="subtitle1" align="center" color="white">
                                {address}
                            </Typography>
                            <ContentCopyIcon
                                htmlColor="white"
                                sx={{ ml: 2, cursor: 'pointer' }}
                                onClick={onCopy}
                            />
                        </Box>
                    </Card>

                    <Typography variant="h6" color="white" sx={{ pb: 1 }}>
                        Enter Transaction hash here
                    </Typography>
                    <TextField
                        variant="standard"
                        onChange={onChangeHash}
                        fullWidth
                        value={hash}
                        required={true}
                        error={isHashInvalid(hash)}
                        placeholder={'Enter Transaction hash here'}
                        autoFocus={true}
                        InputProps={{
                            disableUnderline: true
                        }}
                        sx={{
                            background: '#5148fc',
                            borderRadius: '4px',
                            '& input': {
                                color: '#ffffff',
                                '&::placeholder': {
                                    color: '#ffffff'
                                }
                            },
                            '& .Mui-error': {
                                border: '1px solid #d83a52 !important'
                            },
                            '& .MuiInput-root': {
                                padding: '10px',
                                borderRadius: '4px',
                                border: '1px solid transparent'
                            }
                        }}
                    />

                    <FormControlLabel
                        control={
                            <Checkbox
                                checked={confirmed}
                                onChange={(e) => setConfirmed(e.target.checked)}
                            />
                        }
                        label={
                            <Typography variant="h6" color="white" sx={{ pb: 1, mt: 3 }}>
                                I understand that XLD is not liable in the event that the supplied
                                account details are incorrect
                            </Typography>
                        }
                    />

                    {isTimeout && (
                        <Typography
                            variant="h6"
                            align={'center'}
                            color="white"
                            sx={{
                                marginTop: '1rem',
                                color: 'var(--color-warning-2)'
                            }}
                        >
                            Payment not received within the required window. Transactions won't be
                            sent. Please try to disburse again.
                        </Typography>
                    )}

                    {error && (
                        <Typography
                            variant="h6"
                            align={'center'}
                            color="white"
                            sx={{
                                marginTop: '1rem',
                                color: 'var(--color-negative)'
                            }}
                        >
                            {error.message}
                        </Typography>
                    )}

                    <LoadingButton
                        variant="contained"
                        component="label"
                        onClick={() => submit()}
                        className={`mt-4 w-100 ${style.button}`}
                        loading={loading}
                        disabled={isTimeout || !confirmed}
                    >
                        Submit Verification
                    </LoadingButton>

                    <Button
                        className={`${style.button} mt-4 ${!isTimeout && 'd-none'}`}
                        variant="contained"
                        href={Routes.HOME}
                        fullWidth
                    >
                        Exit Disbursement
                    </Button>
                </div>
            </DialogContent>
        </Dialog>
    );
};
